package com.example.common.core.domain;

import com.example.common.core.enums.ResultCode;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 消息状态码
     */
    private int code;

    /**
     * 消息内容
     */
    private String msg;

    /**
     * 数据对象
     */
    private T data;

    //*****
    public static <T> R<T> ok() {
        return assembleResult(null, ResultCode.SUCCESS);
    }

    public static <T> R<T> ok(T data) {
        return assembleResult(data, ResultCode.SUCCESS);
    }

    public static <T> R<T> fail() {
        return assembleResult(null, ResultCode.FAILED);
    }

    /**
     * 指定错误码
     *
     * @param resultCode 指定错误码
     * @param <T>
     * @return
     */
    public static <T> R<T> fail(ResultCode resultCode) {
        return assembleResult(null, resultCode);
    }

    private static <T> R<T> assembleResult(T data, ResultCode resultCode) {
        R<T> r = new R<>();
        r.setCode(resultCode.getCode());
        r.setData(data);
        r.setMsg(resultCode.getMsg());
        return r;
    }

    public static <T> R<T> ok(String msg, T data) {
        return assembleResult(data, ResultCode.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return assembleResult(null, code, msg);
    }

    public static <T> R<T> fail(String msg) {
        return assembleResult(null, ResultCode.FAILED.getCode(), msg);
    }

    //****
    public static <T> R<T> fail(String msg, ResultCode resultCode) {
        return assembleResult(null, resultCode.getCode(), msg);
    }

    public static <T> R<T> fail(T data) {
        return assembleResult(data, ResultCode.FAILED);
    }

    public static <T> R<T> fail(String msg, T data) {
        return assembleResult(data, ResultCode.FAILED.getCode(), msg);
    }


    private static <T> R<T> assembleResult(T data, int code, String msg) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setData(data);
        r.setMsg(msg);
        return r;
    }

    public static <T> Boolean isError(R<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(R<T> ret) {
        return ResultCode.SUCCESS.getCode() == ret.getCode();
    }


}